import { lazy, Suspense, ReactNode } from "react";
import { Navigate, useLocation } from "react-router-dom";
import LayOut from '../pages/LayOut/LayOut';
import NotFound from '../pages/NotFound/NotFound';

const lazyComponents = {
    LoginIndex: lazy(() => import('../pages/LoginIndex/LoginIndex')),
    DashBoard: lazy(() => import('../pages/DashBoard/DashBoard')),
    UserInfo: lazy(() => import('../pages/UserInfo/UserInfo')),
    SettingPage: lazy(() => import('../pages/SettingPage/SettingPage')),
    NewsList: lazy(() => import('../pages/System/NewsList/NewsList')),
    GoodsList: lazy(() => import('../pages/GoodsList/index')),
    BannerList: lazy(() => import('../pages/System/BannerList/index')),
};

const lazyRoutes = (Component: React.ComponentType): ReactNode => {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <Component />
        </Suspense>
    );
};

const RequireAuth = ({ children }: { children: ReactNode }): ReactNode => {
    const location = useLocation();
    const token = localStorage.getItem('token'); // 假设token存储在localStorage中

    if (!token) {
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    return children;
};

const routes = [
    {
        path: '/',
        element: <Navigate to='/dashboard' />,
    },
    {
        path: '/',
        element: <RequireAuth><LayOut /></RequireAuth>,
        children: [
            {
                path: '/dashboard',
                element: lazyRoutes(lazyComponents.DashBoard)
            },
            {
                path: '/userinfo',
                element: lazyRoutes(lazyComponents.UserInfo)
            },
            {
                path: '/setting',
                element: lazyRoutes(lazyComponents.SettingPage)
            },
            {
                path: '/newsList',
                element: lazyRoutes(lazyComponents.NewsList)
            },
            {
                path: '/goods',
                element: lazyRoutes(lazyComponents.GoodsList)
            },
            {
                path: '/banner',
                element: lazyRoutes(lazyComponents.BannerList)
            }
        ]
    },
    {
        path: '/login',
        element: <lazyComponents.LoginIndex />
    },
    {
        path: '*',
        element: <NotFound />
    }
];

export default routes;
